package utils

import (
	"encoding/json"
	"fmt"
	"github.com/astaxie/beego/logs"
	"io"
	"log"
	"net/http"
	"strings"
	"time"
)

type ZincData struct {
	CreateDate string `json:"create_date"`
	Date       string `json:"date"`
}

func NewZincDataData(date string) *ZincData {
	result := &ZincData{Date: date}
	result.CreateDate = time.Now().Format("2006-01-02 15:04:05")
	return result
}

func InsertDoc(index string, data *ZincData, url, username, pwd string) {
	if index == "" {
		return
	}
	marshal, _ := json.Marshal(data)
	req, err := http.NewRequest("POST", url+"/api/"+index+"/_doc", strings.NewReader(string(marshal)))
	if err != nil {
		log.Fatal(err)
	}
	req.SetBasicAuth(username, pwd)
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36")

	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		logs.Error(err)
	}
	defer resp.Body.Close()
	logs.Info(resp.StatusCode)
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		logs.Error(err)
	}
	fmt.Println(string(body))
}
